import * as request from "request-promise-native";

export var g_des_key = '1EFDEB7504007654D6D41D35B6E0C0181EFDEB7504007654';


export var g_sid = ''
export var g_gray = ''
export var g_urid = ''
export var g_city_code = '110000';
//# 系统初始化请求参数信息
export var sys_init_params = {
    encryptedTk: '05A98230D20F30CC74441032EA25BB2CB97FC034757D2F8FC5FB8222EFC2165E0C3D4517FD21DF5664E741CF74FC118950DFC9775420D10887A1457B75970BB57CBF20B30606AAE8B1E054D6D346A30FA3610F801F068903972D15B0F946E729436FB16C38610D6779D98DB64590C7201B2294F63DD606D1C826FBA375A93749C85CF1EBF4C5E67CD2BE1B0BA4651875B0E7ED54A16D8C086993248D9284338A8DC59EE12DB3460C1718EE031586ACAA73949C03EB8DBBFE0FE868439FAF986CFC20B8777D37F7A927C6A3B247FFF35026E19DF52A635E0A106A81E16EC162DB04503115F93BC3A6D292BAC1D88DDE0D36E60E5C89C8DB24C530EDF188B727C2',
    osName: 'ios',
    clientVersion: "29",
    currentKeyNo: '2',
    encryptedVid: "95E714CE3755E2916F238B2514024E766CEBF7A862E81D81",
    maxKeyNo: '3'
}
import * as crypto from "crypto";
function padding_zero(data: Buffer, is_add: boolean = true) {
    let maxlength = is_add ? (Math.floor(data.length / 8) * 8 + 8) : data.length;
    let temp = new Buffer(maxlength);
    for (let i = 0; i < maxlength; i++) {
        if (i >= data.length) {
            temp.writeUInt8(0, i);
        } else {
            temp.writeUInt8(data[i], i)
        }
    }
    if (is_add == false) {
        while (true) {
            if (temp[maxlength - 1] == 0) {
                maxlength--;
            } else {
                break;
            }
        }
    }
    return temp.slice(0, maxlength);
}
export function des_encrypt(input: string) {
    let buf = padding_zero(new Buffer(input, "utf8"), true);
    //encrypt  
    let keybuf = new Buffer(g_des_key, "hex")
    var cipher = crypto.createCipheriv("des-ede3", keybuf, new Buffer(0));
    cipher.setAutoPadding(false)  //default true  
    var ciph = cipher.update(buf, "binary", 'hex');
    ciph += cipher.final('hex');
    console.log(ciph)
    return ciph;
    // //decrypt  

}
export function des_decrypt(data: string) {
    let keybuf = new Buffer(g_des_key, "hex")
    var decipher = crypto.createDecipheriv("des-ede3", keybuf, new Buffer(0));
    decipher.setAutoPadding(false)
    var txt = decipher.update(data, 'hex', 'utf8');
    txt += decipher.final('utf8');
    console.log(txt);
    txt = padding_zero(new Buffer(txt, "utf8"), false).toString("utf8")
    return txt;
}
export function set_config(key = '', sid = '', gray = '', urid = '', city_code = '') {
    if (key.length > 0)
        g_des_key = key
    if (sid.length > 0)
        g_sid = sid
    if (gray.length > 0)
        g_gray = gray
    if (urid.length > 0)
        g_urid = urid
    if (city_code.length > 0)
        g_city_code = city_code
}

//# 全局配置设置
function buildHeaders() {
    let headers = {
        'Connection': 'keep-alive',
        'User-Agent': 'iPhone CHSP',
        'Accept': '*/*',
        'Accept-Language': 'zh-Hans;q=1',
        'Content-Type': 'application/json'

    }
    if (g_city_code.length > 0) {
        headers['cityCd'] = g_city_code
    }
    if (g_gray.length > 0) {
        headers['gray'] = g_gray
    }
    if (g_sid.length > 0) {
        headers['sid'] = g_sid
    }
    if (g_urid.length > 0) {
        headers['urid'] = g_urid
    }
    return headers;
}
async function app_sys_init() {
    let url = 'https://wallet.95516.com/app/inApp/sys/init'
    let headers = {
        'Connection': 'keep-alive',
        'User-Agent': 'iPhone CHSP',
        'Accept': '*/*',
        'Accept-Language': 'zh-Hans;q=1',
        'Content-Type': 'application/json',
    }
    let r = await request.get({
        uri: url,
        qs: sys_init_params,
        headers: headers,
        json: true // Automatically parses the JSON string in the response
    });
    if (r.resp == "00") {
        let s_key = des_decrypt(r.params.encryptedCk);
        let s_sid = r.params.sid;
        let s_gray = r.params.gray;
        let s_vid = des_decrypt(r.params.encryptedVid);
        set_config(s_key, s_sid, s_gray);
    } else {
        alert(r.msg);
    }

}
async function requestGet(url: string, obj: Object) {
    let qs = undefined;
    if (obj != null) {
        qs = {};
        for (let key in obj) {
            qs[key] = des_encrypt(obj[key]).toUpperCase();
        }
    }

    let r = await request.post({
        uri: url,
        qs: qs,
        headers: buildHeaders(),
        json: false // Automatically parses the JSON string in the response
    })
    let res = des_decrypt(r);
    return JSON.parse(res);
}
async function requestPost(url: string, obj: Object) {

    let r = await request.post({
        uri: url,
        body: obj != null ? des_encrypt(JSON.stringify(obj)).toUpperCase() : undefined,
        headers: buildHeaders(),
        json: false // Automatically parses the JSON string in the response
    })
    let res = des_decrypt(r);
    try {
        return JSON.parse(res);
    } catch (e) {
        return res;
    }

}
//发短信
async function login_sms() {
    return requestPost('https://wallet.95516.com/app/inApp/user/sendLoginCode', {})
}


//# 验证手机短信
async function verify_login_code(verify_code: string) {
    return requestPost('https://wallet.95516.com/app/inApp/user/verifyLoginCode', { smsCode: verify_code })
}
//# 登录接口,通知系统账号登录
async function login(user: string, password: string) {
    return requestPost('https://wallet.95516.com/app/inApp/user/login', {
        password: password,
        loginName: user,
        cntryCode: '+86',
        imageId: '',
        imageCode: ''
    })

}

//# 获取用户信息接口
async function user_info() {
    let data = await requestGet('https://wallet.95516.com/app/inApp/user/get', null);
    let user_id = data.params.urid;
    set_config('', '', '', user_id);
    return data;
}

//# 收款订单列表接口
async function order_list(month: string, pageSize: string) {
    return requestGet('https://wallet.95516.com/app/inApp/order/list', {
        month: month,
        pageSize: pageSize,
        currentPage: '1',
        orderStatus: '0',
        orderType: 'A30000'
    });
}

//# 收款订单详情接口
async function order_detail(orderId: string) {
    return requestPost('https://wallet.95516.com/app/inApp/order/detail', {
        orderId: orderId,
        orderType: "21",
        transTp: "simple"
    })
}

//# 收款二维码初始化接口
async function p2p_pay_init() {
    return requestGet('https://pay.95516.com/pay-web/restlet/qr/p2pPay/getInitInfo', {
        cityCode: g_city_code
    });
}
/*
# 收款二维码生成接口
# money: 收款金额,单位分
# comments: 备注
# virtual_card_no: 收款卡虚拟标志号
# 返回中的 [params]-> [certificate] 就是收款链接,该链接生成的二维码即可以用ying行类app扫描支付*/
async function applay_qrcode(money: number, comments: string, virtual_card_no: string) {
    return requestGet('https://pay.95516.com/pay-web/restlet/qr/p2pPay/applyQrCode', {
        cityCode: g_city_code,
        comments: comments,
        txnAmt: money.toString(),
        virtualCardNo: virtual_card_no
    });
}
async function main() {
    await app_sys_init();
    let info = await login('17757782195', 'Weiwei88')
    if (info.resp == "00") {
        if (info.params.needVerify == "1") {
            info = await login_sms();
            if (info.resp == "00") {

            } else {
                alert(info.msg);
            }
        } else {

        }
    } else {
        alert(info.msg);
    }
}
main()